package com.bangdao.app.jetpacktest;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;

/**
 * @ProjectName: JetpackTest
 * @ClassName: MyApplication
 * @Description: java类作用描述
 * @Author: luhui
 * @Email: hui.lu@bangdao-tech.com
 * @CreateDate: 2022/6/5 12:09
 * @UpdateUser: luhui
 * @UpdateDate: 2022/6/5 12:09
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        //注册App生命周期观察者
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new ApplicationLifecycleObserver());
    }

    /**
     * Application生命周期观察，提供整个应用进程的生命周期
     *
     * Lifecycle.Event.ON_CREATE只会分发一次，Lifecycle.Event.ON_DESTROY不会被分发。
     *
     * 第一个Activity进入时，ProcessLifecycleOwner将分派Lifecycle.Event.ON_START, Lifecycle.Event.ON_RESUME。
     * 而Lifecycle.Event.ON_PAUSE, Lifecycle.Event.ON_STOP，将在最后一个Activit退出后后延迟分发。如果由于配置更改而销毁并重新创建活动，则此延迟足以保证ProcessLifecycleOwner不会发送任何事件。
     *
     * 作用：监听应用程序进入前台或后台
     */
    private static class ApplicationLifecycleObserver implements DefaultLifecycleObserver {

        @Override
        public void onStart(@NonNull LifecycleOwner owner) {
            Log.w(CommonConstant.TAG, "ApplicationObserver: app moved to foreground");
        }

        @Override
        public void onStop(@NonNull LifecycleOwner owner) {
            Log.w(CommonConstant.TAG, "ApplicationObserver: app moved to background");
        }
    }
}
